/*
 *
 * -------------------------------------------------------------------------------------------------
 *                            COPYRIGHT(C) BOCO HEALTH 2016
 * -------------------------------------------------------------------------------------------------
 *
 * =================================================================================================
 *  *HISTORY
 *
 *      Tag                Date            Author           Description
 * =================================================================================================
 *      created            2017/1/17      caodailu        create
 * =================================================================================================
 *
 *
 */

package com.boco.base.view.im;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.contact.IYWContactService;
import com.alibaba.mobileim.conversation.IYWMessageListener;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.conversation.YWMessage;
import com.alibaba.mobileim.gingko.presenter.contact.IContactProfileUpdateListener;
import com.alibaba.mobileim.lib.model.message.YWSystemMessage;
import com.boco.base.App;
import com.boco.base.R;
import com.boco.base.base.BaseActivity;
import com.boco.base.view.main.MainActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ContactSystemMessageActivity extends BaseActivity {

    @BindView(R.id.head_center_text)
    TextView mHeadCenterText;
    @BindView(R.id.head_right_text)
    TextView mHeadRightText;

    private ContactSystemMessageAdapter mAdapter;
    private ListView mListView;
    private List<YWMessage> mList = new ArrayList<YWMessage>();
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private YWIMKit imKit;
    private YWConversation mConversation;
    private IContactProfileUpdateListener iContactProfileUpdateListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        contentView(R.layout.activity_contact_system_message);
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        initTitle();
        imKit = App.getYwimKit();
        mListView = (ListView) findViewById(R.id.message_list);
        mConversation = imKit.getConversationService().getCustomConversationByConversationId
                (MainActivity.SYSTEM_FRIEND_REQ_CONVERSATION);
        mList = mConversation.getMessageLoader().loadMessage(20, null);
        mAdapter = new ContactSystemMessageAdapter(imKit.getUserContext(), this, mList);
        mListView.setAdapter(mAdapter);
        imKit.getConversationService().markReaded(mConversation);

        //添加新消息到达监听,监听到有新消息到达的时候或者消息类别有变更的时候应该更新adapter
        mConversation.getMessageLoader().addMessageListener(mMessageListener);

        iContactProfileUpdateListener = new IContactProfileUpdateListener() {
            @Override
            public void onProfileUpdate() {

            }

            @Override
            public void onProfileUpdate(String userid, String appkey) {
                refreshAdapter();
            }
        };
        imKit.getContactService().addProfileUpdateListener(iContactProfileUpdateListener);

    }


    IYWMessageListener mMessageListener = new IYWMessageListener() {
        @Override
        public void onItemUpdated() {  //消息列表变更，例如删除一条消息，修改消息状态，加载更多消息等等
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mAdapter.notifyDataSetChangedWithAsyncLoad();
                }
            });
        }

        @Override
        public void onItemComing() { //收到新消息
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mAdapter.notifyDataSetChangedWithAsyncLoad();
                    if (imKit != null && imKit.getConversationService() != null)
                        imKit.getConversationService().markReaded(mConversation);

                }
            });
        }

        @Override
        public void onInputStatus(byte status) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mConversation.getMessageLoader().removeMessageListener(mMessageListener);

    }


    private void initTitle() {

        mHeadCenterText.setVisibility(View.VISIBLE);
        mHeadCenterText.setText("联系人系统消息");
        mHeadRightText.setVisibility(View.VISIBLE);
        mHeadRightText.setText("清空");

    }

    private void refreshAdapter() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mAdapter.refreshData(mList);
            }
        });
    }

    private IYWContactService getContactService() {
        return App.getYwimKit().getContactService();
    }

    public void acceptToBecomeFriend(final YWMessage message) {
        final YWSystemMessage msg = (YWSystemMessage) message;
        if (getContactService() != null) {
            getContactService().ackAddContact(message.getAuthorUserId(), message.getAuthorAppkey
                    (), true, "", new IWxCallback() {
                @Override
                public void onSuccess(Object... result) {
                    msg.setSubType(YWSystemMessage.SYSMSG_TYPE_AGREE);
                    refreshAdapter();
                    getContactService().updateContactSystemMessage(msg);
                }

                @Override
                public void onError(int code, String info) {

                }

                @Override
                public void onProgress(int progress) {

                }
            });
        }
    }

    public void refuseToBecomeFriend(YWMessage message) {
        final YWSystemMessage msg = (YWSystemMessage) message;

        if (getContactService() != null) {
            getContactService().ackAddContact(message.getAuthorUserId(), message.getAuthorAppkey
                    (), false, "", new IWxCallback() {
                @Override
                public void onSuccess(Object... result) {
                    msg.setSubType(YWSystemMessage.SYSMSG_TYPE_IGNORE);
                    refreshAdapter();
                    getContactService().updateContactSystemMessage(msg);
                }

                @Override
                public void onError(int code, String info) {

                }

                @Override
                public void onProgress(int progress) {

                }
            });
        }

    }

    @OnClick({R.id.head_left_show, R.id.head_right_show})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.head_left_show:
                finish();
                break;
            case R.id.head_right_show:
                mConversation.getMessageLoader().deleteAllMessage();
                break;
        }
    }
}